package com.presto.directo.base

import android.app.Dialog
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.hjq.bar.OnTitleBarListener
import com.hjq.bar.TitleBar
import com.presto.directo.R
import com.presto.directo.entity.LoanStatusEntity
import com.presto.directo.mvvm.viewmodel.loanStatus
import com.presto.directo.net.getHttpMap
import com.presto.directo.net.sign
import com.presto.directo.utils.*
import es.dmoral.toasty.Toasty
import kotlinx.coroutines.*
import org.json.JSONObject

abstract class BaseActivity : AppCompatActivity(), CoroutineScope by MainScope() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        rootView?.let {
            setContentView(it)
        }
        if (isTransparentStatusBar()) {
            window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
        }
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        window.statusBarColor = if (isTransparentStatusBar()) Color.TRANSPARENT else getStatusBarColor()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!isDarkStatusBar()) {
                window.decorView.systemUiVisibility = window.decorView.systemUiVisibility or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            } else {
                window.decorView.systemUiVisibility = window.decorView.systemUiVisibility and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv()
            }
        }
        findViewById<TitleBar>(R.id.title_bar)?.setOnTitleBarListener(object : OnTitleBarListener {
            override fun onLeftClick(view: View?) {
                back()
            }

            override fun onTitleClick(view: View?) {

            }

            override fun onRightClick(view: View?) {

            }
        })
        initEvent()
        start(onNext = {
            val result = getApiService().getIpAddress().string()
            result.run {
                val start = this.indexOf("{")
                val end = this.indexOf("}") + 1
                val json = this.substring(start, end)
                val ip = JSONObject(json).optString("cip")
                SPUtil.put("ipAddress", ip)
            }
        }, toast = false)
        start(onNext = {
            val config = getApiService().getConfig(getHttpMap().sign(2)).result
            SPUtil.putObject("config", config)
        }, toast = false)
    }

    open fun initEvent() {}
    open fun updateBtn() {}
    open fun isTransparentStatusBar(): Boolean {
        return false
    }

    open fun getStatusBarColor(): Int {
        return ContextCompat.getColor(this, R.color.white)
    }

    open fun isDarkStatusBar(): Boolean {
        return false
    }

    open fun back() {
        finish()
    }


    abstract val rootView: View?

    private lateinit var progress: Dialog

    fun showProgress() {
        if (!this::progress.isInitialized) {
            progress = Dialog(this, R.style.BaseDialog)
            progress.window?.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
            progress.setContentView(R.layout.layout_progress)
            progress.setCanceledOnTouchOutside(false)
        }
        progress.show()
    }

    fun dismissProgress() {
        if (this::progress.isInitialized && progress.isShowing) {
            progress.dismiss()
        }
    }

    fun toast(msg: CharSequence?) {
        if (msg.isNullOrBlank()) return
        Toasty.info(this, msg, Toasty.LENGTH_SHORT).show()
    }

    fun toast(@StringRes res: Int) {
        Toasty.info(this, getString(res), Toasty.LENGTH_SHORT).show()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (this::progress.isInitialized) {
            progress.dismiss()
        }
        cancel()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putSerializable("status", loanStatus)
    }

    override fun onRestoreInstanceState(savedInstanceState: Bundle) {
        super.onRestoreInstanceState(savedInstanceState)
        loanStatus = savedInstanceState.getSerializable("status") as LoanStatusEntity
    }
}